package com.falling.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.falling.reggie.common.BaseContext;
import com.falling.reggie.common.R;
import com.falling.reggie.entity.AddressBook;
import com.falling.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/addressBook")
@Slf4j
public class AddressBookController {

    @Resource
    private AddressBookService addressBookService;

    @PostMapping
    public R<AddressBook> save(@RequestBody AddressBook addressBook){
        // 设置userId
        addressBook.setUserId(BaseContext.getCurrentId());

        if (addressBookService.save(addressBook)) return R.success(addressBook);
        else return R.error("save fail...");
    }

    @PutMapping("/default")
    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook){

        if (addressBookService.setDefaultAddress(addressBook)) return R.success(addressBook);
        else return R.error("set default fail...");

    }

    @GetMapping("/{id}")
    public R<AddressBook> get(@PathVariable Long id){
        AddressBook addressBook = addressBookService.getById(id);
        if (addressBook != null) return R.success(addressBook);
        else return R.error("get address fail...");
    }

    @GetMapping("/default")
    public R<AddressBook> getDefault(){
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getIsDefault, 1);
        queryWrapper.eq(AddressBook::getUserId, userId);
        AddressBook addressBook = addressBookService.getOne(queryWrapper);
        if (addressBook != null) return R.success(addressBook);
        else return R.error("get default address fail...");
    }

    @GetMapping("/list")
    public R<List<AddressBook>> list(){

        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(AddressBook::getUserId, userId);
        queryWrapper.orderByDesc(AddressBook::getUpdateTime);
        List<AddressBook> list = addressBookService.list(queryWrapper);
        return R.success(list);
    }

    @PutMapping
    public R<String> updateAds(@RequestBody AddressBook addressBook){

        log.info("address = " + addressBook.toString());
        if (addressBookService.updateById(addressBook)) return R.success("update address success...");
        else return R.error("update address fail...");

    }
}
